//
//  PENationalAgencyApplySelectProductVC.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2023/7/25.
//

#import "RHAgencyApplySelectProductVC.h"
#import <YYText/YYText.h>
#import "RHAgencyApplyResultVC.h"
#import "RHProductTypeModel.h"
#import "RHPdfFileModel.h"
#import "RHBaseWebViewController.h"

@interface RHAgencyApplySelectProductVC ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic ,strong) UITableView *tableView;
@property(nonatomic ,strong)NSArray *productArr;
//附件上传索引
@property(nonatomic,assign)NSInteger attach_index;
//附件上传子索引
@property(nonatomic,assign)NSInteger attach_sub_index;
//图片营业执照licenseUrl字段,里面要存json字符串数组
@property(nonatomic ,strong)NSMutableArray *licenseArr;
//请求参数的key,与后台相同
@property (nonatomic ,strong)NSArray *agencyKeyArr;
//
@property (nonatomic ,strong)NSMutableArray *insterestedProductArr;

//勾选按钮
@property (nonatomic ,strong)QMUIButton *agreeBtn;
@end

@implementation RHAgencyApplySelectProductVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"National agency Apply";
    self.view.backgroundColor = kRGB(247, 247, 247);
    [self setupUI];
    [self getDeviceType];
    NSLog(@"----->要请求的参数%@",self.para);
}

-(void)getDeviceType
{
    [QMUITips showLoading:@"loading product type..." inView:self.view];
    [BaseModel startGetWithCompletionAPIKey:H_productTypeList argument:@{} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if (resultModel.code == 200) {
          self.productArr =  [NSArray yy_modelArrayWithClass:[RHProductTypeModel class] json:request.responseObject[@"rows"]];
            [self.tableView reloadData];
            
            //默认选择第一个
            RHProductTypeModel *model = self.productArr[0];
            [self.para setObject:model.productTypeCode forKey:@"productTypeId"];
        }
        } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            
        }];
}
-(void)setupUI{
    _insterestedProductArr = [NSMutableArray array];
    _licenseArr = [NSMutableArray array];
    _agencyKeyArr = @[@[@"certificationDescribe",@"certificationFile"],//企业资质
                      @[@"financeDescribe",@"financeFile"],//财务状况
                      @[@"planDescribe",@"planFile"],//市场分析和商业计划
                      @[@"siteDescribe",@"siteFile"],//场地和设施
                      @[@"teamDescribe",@"teamFile"],//人员组成和团队管理
                      @[@"marketingDescribe",@"marketingFile"],//推广
                      @[@"otherDescribe",@"otherFile"]];//其他
    
    UILabel *lab = [[UILabel alloc]initWithFrame:CGRectMake(5, 5, 200, 10)];
    lab.font = [UIFont systemFontOfSize:16];
    lab.text = @"Please Select The Product You Are Interested In";
    [self.view addSubview:lab];
    [lab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view).offset(15);
            make.top.equalTo(self.view).offset(15);
    }];
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    [_tableView setBackgroundColor:UIColor.whiteColor];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];
    [_tableView setSeparatorColor:kRGB(240, 240, 240) ];
    _tableView.estimatedRowHeight = 500;
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    _tableView.layer.cornerRadius = 8;
    _tableView.layer.masksToBounds = YES;
    [self.view addSubview:_tableView];
    if (@available(iOS 11.0, *)) {
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    if (@available(iOS 15.0, *)) {
        _tableView.sectionHeaderTopPadding = 0;
    }
    kWeakSelf;
    //提交下一步
    QMUIButton *submitBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:submitBtn];
    [submitBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    submitBtn.titleLabel.font = [UIFont systemFontOfSize:kScaleW(20)];
    [submitBtn setTitle:@"提交".rh_localized forState:UIControlStateNormal];
    [submitBtn setCornerRadius:10];
    [submitBtn setBackgroundColor:CMainColorGreen];
    [submitBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.view).offset(15);
        make.right.equalTo(weakSelf.view).offset(-15);
        make.height.offset(kScaleW(60));
        make.bottom.equalTo(weakSelf.view).offset(-(kSafe_bottom+10));
    }];
    
    //勾选按钮
    QMUIButton *agreeBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:agreeBtn];
    [agreeBtn setImage:[UIImage imageNamed:@"agree"] forState:UIControlStateSelected];
    [agreeBtn setContentEdgeInsets:UIEdgeInsetsMake(5, 5, 5, 5 )];
    [agreeBtn setCornerRadius:5];
    agreeBtn.layer.borderColor = kRGB(140, 140, 140).CGColor;
    agreeBtn.layer.borderWidth = 1;
    self.agreeBtn = agreeBtn;
    [agreeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.offset(20);
        make.height.equalTo(agreeBtn.mas_width);
        make.left.equalTo(submitBtn).offset(20);
        make.bottom.equalTo(submitBtn.mas_top).offset(-20);
    }];
    [[agreeBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        x.selected = !x.selected;
    }];

    [submitBtn addTarget:self action:@selector(submitAction) forControlEvents:UIControlEventTouchUpInside];
    //协议
    NSString *str = @"Please carefully review and read the 《National Agent User Agreement》";
    NSRange range1 = [str rangeOfString:@"《National Agent User Agreement》"];
    
    YYLabel *contentL = [[YYLabel alloc] init];
    //设置多行
    contentL.numberOfLines = 0;
    //这个属性必须设置，多行才有效
    contentL.preferredMaxLayoutWidth = kUI_WINDOW_W-40-30;
    NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:str];
    attri.yy_lineSpacing = 8;
    attri.yy_font = [UIFont systemFontOfSize:16];
    attri.yy_color = [UIColor colorWithHexString:@"#333333"];
    
    [attri yy_setTextHighlightRange:range1 color:[UIColor colorWithHexString:@"#3ECE80"] backgroundColor:[UIColor clearColor] tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        RHBaseWebViewController *webVC = [[RHBaseWebViewController alloc]init];
        [webVC setLocalHtml:@"terms_of_use"];
        webVC.navTitle = @"National Agent User Agreement";
        [weakSelf.navigationController pushViewController:webVC animated:YES];
       
    }];
    //用label的attributedText属性来使用富文本
    contentL.attributedText = attri;
    CGSize maxSize = CGSizeMake(kUI_WINDOW_W-40-30, MAXFLOAT);
    //计算文本尺寸
    YYTextLayout *layout = [YYTextLayout layoutWithContainerSize:maxSize text:attri];
    contentL.textLayout = layout;
    CGFloat introHeight = layout.textBoundingSize.height;
//    [contentL setBackgroundColor:[UIColor whiteColor]];
    [self.view addSubview:contentL];
    
    [contentL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(agreeBtn.mas_right).offset(15);
        make.centerY.equalTo(agreeBtn);
        make.height.mas_equalTo(introHeight);
      
    }];
    
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(lab);
        make.right.equalTo(weakSelf.view).offset(-15);
        make.top.equalTo(lab.mas_bottom).offset(15);
        make.bottom.equalTo(contentL.mas_top).offset(-15);
    }];
    
}
#pragma mark -------- 身份证,营业执照,法人证件 图片上传 ----------------
-(void)uploadLisenceImageWith:(UIImage *)image
{
    kWeakSelf;
    [QMUITips showLoading:@"upload  image ..." inView:self.view];
    [BaseModel startUploadWithCompletionAPIKey:H_uploadImage rgument:@{@"file":@"agencyApply"} image:image imageName:nil requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            
            //这里要组装成json字符串
            /*[{"name":"2334.jpg_wh860.jpg",
                "url":"/profile/upload/2023/08/07/2334.jpg_wh860_20230807185730A002.jpg",
                "fileUrl":"http://192.168.0.133:9091/profile/upload/2023/08/07/2334.jpg_wh860_20230807185730A002.jpg",
                "uid":1691405852820,"status":"success"}]
            */
            NSString *newFileName = request.responseObject[@"newFileName"];
            NSString *imgName = [[newFileName componentsSeparatedByString:@"_"]lastObject];
            NSMutableDictionary *mtbDic = [NSMutableDictionary dictionary];
            [mtbDic setObject:imgName forKey:@"name"];
            [mtbDic setObject:request.responseObject[@"fileName"] forKey:@"url"];
            [mtbDic setObject:request.responseObject[@"url"] forKey:@"fileUrl"];
            NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
            formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
            NSString *timeStr = [formatter stringFromDate:[NSDate date]];
            [mtbDic setObject:timeStr forKey:@"uid"];
            //四张图片,前三张是身份证和营业执照,最后一张是法人资料
            [weakSelf.licenseArr addObject:mtbDic];
    
            weakSelf.attach_index++;
            //图片上传完了,上传文件
            if(weakSelf.attach_index == weakSelf.imageMuArr.count){
                //取出最后一张法人图片
                NSMutableArray *legalArr = [NSMutableArray array];
                [legalArr addObject: [weakSelf.licenseArr lastObject]];
                //去掉法人的图片信息,只留身份证和营业执照
                [weakSelf.licenseArr removeLastObject];
                //将字典数组转成字符串
                NSString *licenseStr = [weakSelf.licenseArr yy_modelToJSONString];
                licenseStr = [licenseStr stringByReplacingOccurrencesOfString:@"\n" withString:@""];
                licenseStr = [licenseStr stringByReplacingOccurrencesOfString:@"\\" withString:@""];
                while ([licenseStr containsString:@" "]) {
                    licenseStr = [licenseStr stringByReplacingOccurrencesOfString:@" " withString:@""];
                }
                [weakSelf.para setObject:licenseStr forKey:@"licenseUrl"];//身份证,营业执照
                
                NSString *legalStr = [legalArr yy_modelToJSONString];
                legalStr = [legalStr stringByReplacingOccurrencesOfString:@"\n" withString:@""];
                legalStr = [legalStr stringByReplacingOccurrencesOfString:@"\\" withString:@""];
                while ([legalStr containsString:@" "]) {
                    legalStr = [legalStr stringByReplacingOccurrencesOfString:@" " withString:@""];
                }
                [weakSelf.para setObject:legalStr forKey:@"legalPersonFile"];//法人信息
                //重置上传计数,开始上传附件,每一个附件里包含 文件,图片,
                self.attach_index = 0;
                self.attach_sub_index = 0;
                [self.licenseArr removeAllObjects];
                [weakSelf uploadAttachment];
            }else{
                //继续上传下一张图片
                UIImage *image = weakSelf.imageMuArr[weakSelf.attach_index];
                [weakSelf uploadLisenceImageWith:image];
                
            }
           
          }
        
        } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
           
        }];
}

#pragma mark -------- 上传附件 ----
-(void)uploadAttachment
{
    
    if(self.attach_index == self.pdfFileArr.count){
        //附件上传完了
        [self ApplyingForCooperation];
        return;
    }
    NSLog(@"---->上传第%zd组第%zd个附件",self.attach_index,self.attach_sub_index);
    NSMutableArray *attachmentArr = self.pdfFileArr[self.attach_index];
    RHPdfFileModel *fileModel = attachmentArr[self.attach_sub_index];
    if(fileModel.image){
        NSLog(@"---->上传附件图片");
        [self uploadAttachmentImageWith:fileModel.image imageName:fileModel.fileName imageSize:fileModel.fileSize];
    }else{
        NSLog(@"---->上传附件文件");
        [self uploadFileWithFilePath:fileModel.filePath fileSize:fileModel.fileSize];
    }
    
}

#pragma mark -------- 附件 图片 上传 ----------------
-(void)uploadAttachmentImageWith:(UIImage *)image imageName:(NSString*)imageName imageSize:(NSString*)imageSize
{
    kWeakSelf;
    [QMUITips showLoading:@"upload  attachment image ...." inView:self.view];
    [BaseModel startUploadWithCompletionAPIKey:H_uploadImage rgument:@{@"file":@"attachImage"} image:image imageName:imageName requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            
            //这里要组装成json字符串
            /*[{"name":"2334.jpg_wh860.jpg",
                "url":"/profile/upload/2023/08/07/2334.jpg_wh860_20230807185730A002.jpg",
                "fileUrl":"http://192.168.0.133:9091/profile/upload/2023/08/07/2334.jpg_wh860_20230807185730A002.jpg",
                "uid":1691405852820,"status":"success"}]
            */
            NSString *newFileName = request.responseObject[@"newFileName"];
            NSString *imgName = [[newFileName componentsSeparatedByString:@"_"]lastObject];
            NSMutableDictionary *mtbDic = [NSMutableDictionary dictionary];
            [mtbDic setObject:imgName forKey:@"name"];
            [mtbDic setObject:request.responseObject[@"fileName"] forKey:@"url"];
            [mtbDic setObject:request.responseObject[@"url"] forKey:@"fileUrl"];
            [mtbDic setObject:imageSize forKey:@"fileSize"];
            NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
            formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
            NSString *timeStr = [formatter stringFromDate:[NSDate date]];
            [mtbDic setObject:timeStr forKey:@"uid"];
            
            [self.licenseArr addObject:mtbDic];
            
           
    
            self.attach_sub_index++;
            NSMutableArray *attachmentArr = self.pdfFileArr[self.attach_index];
            if(self.attach_sub_index == attachmentArr.count){
                
                //一组附件全部上传完了
                //将字典数组转成字符串
                NSString *licenseStr = [weakSelf.licenseArr yy_modelToJSONString];
                licenseStr = [licenseStr stringByReplacingOccurrencesOfString:@"\n" withString:@""];
                licenseStr = [licenseStr stringByReplacingOccurrencesOfString:@"\\" withString:@""];
                while ([licenseStr containsString:@" "]) {
                    licenseStr = [licenseStr stringByReplacingOccurrencesOfString:@" " withString:@""];
                }
                //文件描述在0下标,上传后的文件信息在1下标
                NSString *paraKey = weakSelf.agencyKeyArr[weakSelf.attach_index][1];
                [weakSelf.para setObject:licenseStr forKey:paraKey];
                
                //移除之前存放的图片内容
                [self.licenseArr removeAllObjects];
                
                //一个附件全部上传完了,上传第二个附件
                self.attach_index++;
                self.attach_sub_index = 0;
                [self uploadAttachment];
            }else{
                //接着上传附件里的其他文件
                [self uploadAttachment];
            }
        
          }
        
        } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
           
        }];
}




#pragma mark -------- pdf文件上传 ----------------
-(void)uploadFileWithFilePath:(NSString*)filePath fileSize:(NSString*)fileSize
{
    kWeakSelf;
    [QMUITips showLoading:@"upload pdf file...." inView:self.view];
    [BaseModel startUploaFiledWithCompletionAPIKey:H_uploadImage rgument:@{} filePath:filePath requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            
            
            //这里url要组装成 json 数组
            NSString *newFileName = request.responseObject[@"newFileName"];
            NSString *fileName = [[newFileName componentsSeparatedByString:@"_"]lastObject];
            NSMutableDictionary *mtbDic = [NSMutableDictionary dictionary];
            [mtbDic setObject:fileName forKey:@"name"];
            [mtbDic setObject:request.responseObject[@"fileName"] forKey:@"url"];
            [mtbDic setObject:request.responseObject[@"url"] forKey:@"fileUrl"];
            [mtbDic setObject:fileSize forKey:@"fileSize"];
            NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
            formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
            NSString *timeStr = [formatter stringFromDate:[NSDate date]];
            [mtbDic setObject:timeStr forKey:@"uid"];
            [weakSelf.licenseArr addObject:mtbDic];
            
            self.attach_sub_index++;
            NSMutableArray *attachmentArr = self.pdfFileArr[self.attach_index];
            if(self.attach_sub_index == attachmentArr.count){
                //一个附件全部上传完了
                //将字典数组转成字符串
                NSString *licenseStr = [weakSelf.licenseArr yy_modelToJSONString];
                licenseStr = [licenseStr stringByReplacingOccurrencesOfString:@"\n" withString:@""];
                licenseStr = [licenseStr stringByReplacingOccurrencesOfString:@"\\" withString:@""];
                while ([licenseStr containsString:@" "]) {
                    licenseStr = [licenseStr stringByReplacingOccurrencesOfString:@" " withString:@""];
                }
               
                //文件描述在0下标,上传后的文件信息在1下标
                NSString *paraKey = weakSelf.agencyKeyArr[weakSelf.attach_index][1];
                [weakSelf.para setObject:licenseStr forKey:paraKey];
                
                //移除之前存放的图片内容
                [self.licenseArr removeAllObjects];
                
                //上传第二个附件
                self.attach_index++;
                self.attach_sub_index = 0;
                [self uploadAttachment];
            }else{
                //接着上传附件里的其他文件
                [self uploadAttachment];
            }
        }
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
        
    }];
}
#pragma mark -------压缩图片质量   maxLength  单位: kb
- (UIImage *)compressImageQuality:(UIImage *)image toByte:(NSInteger)maxLength {
    
     CGFloat compression = 1;
     NSData *data = UIImageJPEGRepresentation(image, compression);
     while (data.length / 1024 > maxLength && compression > 0) {
         compression -= 0.05;
         // When compression less than a value, this code dose not work
         data = UIImageJPEGRepresentation(image, compression);
         NSLog(@"====>压缩了一次后: %ld k",(long)(data.length / 1024));
     }
     UIImage *resultImage = [UIImage imageWithData:data];
     return resultImage;
}


#pragma mark ------- 提交审核 -----
-(void)ApplyingForCooperation{
    NSLog(@"---->final para:%@",self.para);
    [QMUITips showLoading:@"Submit for review..." inView:self.view];
    [BaseModel startWithCompletionAPIKey:H_addPartner argument:self.para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            if(resultModel.code == 200){
               [self.navigationController pushViewController:[[RHAgencyApplyResultVC alloc]init] animated:YES];
            }
        } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            
        }];
   
}

#pragma mark ------- 点击提交按钮 -----
-(void)submitAction
{
//    NSLog(@"----->request para:%@",self.para);
//    NSLog(@"---->picture :%@",self.imageMuArr);
//    NSLog(@"---->pdf file:%@",self.pdfFileArr);
    
   
    
    if(self.insterestedProductArr.count == 0){
        [QMUITips showError:@"please select product"];
        return;
    }
    
    if(self.agreeBtn.selected == NO){
        [QMUITips showError:@"Please agree to the 《National Agent User Agreement》"];
        return;
    }
    
    [self.licenseArr removeAllObjects];
    NSMutableArray *tempArr = [NSMutableArray array];
    [QMUITips showLoading:@"compressing..." inView:self.view];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        for (id img in self.imageMuArr) {
            if([img isKindOfClass:[UIImage class]]){
                UIImage *compressImage = [self compressImageQuality:img toByte:5000];
                [tempArr addObject:compressImage];
            }
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [QMUITips hideAllTipsInView:self.view];
            self.imageMuArr = tempArr;
            self.attach_index = 0;
            [self uploadLisenceImageWith:self.imageMuArr[0]];
        });
    });
    
    

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.productArr.count;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"product"];
    if(cell==nil)
    {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"product"];
    }
    RHProductTypeModel *model = self.productArr[indexPath.row];
    cell.textLabel.text = model.productTypeName;
    cell.textLabel.font = [UIFont systemFontOfSize:15];
    if(model.isSelected)
    {
        UIImageView *rightImg = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 20, 20)];
        rightImg.image = [UIImage imageNamed:@"submit_success"];
        cell.accessoryView = rightImg;
    }else{
        cell.accessoryView = nil;
    }
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    RHProductTypeModel *model = self.productArr[indexPath.row];
    model.isSelected = !model.isSelected;
    if(model.isSelected){
        [self.insterestedProductArr addObject:@([model.productType_id integerValue])];
    }else{
        //删除
        NSInteger idx=0;
        for (NSInteger i=0; i<self.insterestedProductArr.count; i++) {
            NSNumber *productID = self.insterestedProductArr[i];
            if([productID integerValue] == [model.productType_id integerValue]){
                idx = i;
                break;
            }
        }
        [self.insterestedProductArr removeObjectAtIndex:idx];
    }
    [self.para setObject:self.insterestedProductArr forKey:@"productTypeId"];
    [tableView reloadData];
}
@end
